package top.itaso.app.ui.picker;

import android.app.Application;

import androidx.lifecycle.AndroidViewModel;

import com.google.gson.Gson;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import top.itaso.app.R;
import top.itaso.lib.alog.ALog;
import top.itaso.lib.widget.AutoFilterInputEditView;

public class PickerViewModel extends AndroidViewModel {
    private static final String TAG = "PickerViewModel";

    public PickerViewModel(Application application) {
        super(application);
    }

    /**
     * 从 res/raw中读取 Excel 文件数据
     *
     * @return
     */
    public ArrayList<AutoFilterInputEditView.Node> readOrgMemberFromExcel() {
        ArrayList<OrgMemberBean> orgMemberBeans = new ArrayList<>();
        InputStream stream = getApplication().getResources().openRawResource(R.raw.orgmember);
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(stream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            int rowsCount = sheet.getPhysicalNumberOfRows();//获取总行数
            ALog.dTag(TAG, "rowsCount:%s", rowsCount);
            FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
            //每次读取一行的内容
            for (int i = 1; i < rowsCount; i++) {//i从1开始是去掉Excel里第一行是title，它不是我们想要的数据
                Row row = sheet.getRow(i);
                int cellsCount = row.getPhysicalNumberOfCells();
                ALog.dTag(TAG, "cellsCount:%s", cellsCount);
                OrgMemberBean orgMemberBean = new OrgMemberBean();
                orgMemberBean.setId(getCellAsString(row, 0, formulaEvaluator));
                orgMemberBean.setPid(getCellAsString(row, 1, formulaEvaluator));
                orgMemberBean.setLevel(Integer.parseInt(getCellAsString(row, 2, formulaEvaluator)));
                orgMemberBean.setTitle(getCellAsString(row, 3, formulaEvaluator));
                orgMemberBean.setOwner(getCellAsString(row, 4, formulaEvaluator));
                orgMemberBeans.add(orgMemberBean);
//                for (int j = 0; j < cellsCount; j++) {
//                    //将每一格子的内容转换为字符串形式
//                    String value = getCellAsString(row, j, formulaEvaluator);
//                    String cellInfo = "r:" + i + "; c:" + j + "; v:" + value;
//                    ALog.dTag(TAG, "cellInfo:%s", cellInfo);
//                }
            }
        } catch (Exception e) {
            ALog.eTag(TAG, "e:%s", e);
        }
        String dataJson = new Gson().toJson(orgMemberBeans);
        return parseOrgMembers(dataJson);
    }

    public ArrayList<AutoFilterInputEditView.Node> getLevelNode(ArrayList<AutoFilterInputEditView.Node> nodes, int level) {
        ArrayList<AutoFilterInputEditView.Node> resultLevelNode = new ArrayList<>();
        for (AutoFilterInputEditView.Node node : nodes) {
            if (node.getLevel() == level) {
                resultLevelNode.add(node);
            }
        }
        return resultLevelNode;
    }


    /**
     * Demo数据
     *
     * @param orgMembers [{"id":"0000000000","level":0,"owner":"aso","pid":"0000000000","title":"超级管理员"},{"id":"0100000000","level":1,"owner":"张三","pid":"0000000000","title":"运营部主管"},{"id":"0101000000","level":2,"owner":"赵六","pid":"0100000000","title":"运营部副主管"},{"id":"0102000000","level":2,"owner":"孙七","pid":"0100000000","title":"运营部副主管"},{"id":"0200000000","level":1,"owner":"李四","pid":"0000000000","title":"市场部主管"},{"id":"0201000000","level":2,"owner":"周八","pid":"0200000000","title":"市场部副主管"},{"id":"0202000000","level":2,"owner":"吴九","pid":"0200000000","title":"市场部副主管"},{"id":"0203000000","level":2,"owner":"郑十","pid":"0200000000","title":"市场部副主管"},{"id":"0300000000","level":1,"owner":"王五","pid":"0000000000","title":"研发部主管"},{"id":"0301000000","level":2,"owner":"二嘎","pid":"0300000000","title":"研发部副主管"},{"id":"0302000000","level":2,"owner":"一血","pid":"0300000000","title":"研发部副主管"},{"id":"0302010000","level":3,"owner":"itsdf07","pid":"0302000000","title":"研发部一组组长"},{"id":"0302020000","level":3,"owner":"itsdf01","pid":"0302000000","title":"研发部二组组长"}]
     * @return
     */
    private ArrayList<AutoFilterInputEditView.Node> parseOrgMembers(String orgMembers) {
        ArrayList<AutoFilterInputEditView.Node> orgMemberBeans = new ArrayList<>();
        try {
            JSONArray orgMemberArray = new JSONArray(orgMembers);
            Gson gson = new Gson();
            for (int i = 0; i < orgMemberArray.length(); i++) {
                OrgMemberBean bean = gson.fromJson(orgMemberArray.getString(i), OrgMemberBean.class);
                AutoFilterInputEditView.Node member = new AutoFilterInputEditView.Node(bean.getId(), bean.getPid(), bean.getLevel(), bean.getTitle());
                member.setData(bean);
                orgMemberBeans.add(member);
            }
            ALog.dTag(TAG, "Node size:%s", orgMemberBeans.size());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        convertData2Node(orgMemberBeans);
        return orgMemberBeans;
    }

    /**
     * 将我们的数据转化为树型关系的节点
     * 设置 Node 间，父子关系;让每两个节点都比较一次，即可设置其中的关系
     *
     * @param nodes 节点数据
     */
    private static List<AutoFilterInputEditView.Node> convertData2Node(List<AutoFilterInputEditView.Node> nodes) {
        for (int i = 0; i < nodes.size(); i++) {
            AutoFilterInputEditView.Node n = nodes.get(i);
            for (int j = i + 1; j < nodes.size(); j++) {
                AutoFilterInputEditView.Node m = nodes.get(j);
                if (m.getPid() instanceof String) {
                    if (m.getPid().equals(n.getId())) {//判断 n 和 m 的关系为 n 是 m 的父节点关系
                        n.getChildren().add(m);//设置 m 为 n 的子节点
                        m.setParentNode(n);//设置 n 为 m 的父节点
                    } else if (m.getId().equals(n.getPid())) {//判断 n 和 m 的关系为 m 是 n 的父节点关系
                        m.getChildren().add(n);
                        n.setParentNode(m);
                    }
                } else {
                    if (m.getPid() == n.getId()) {
                        n.getChildren().add(m);
                        m.setParentNode(n);
                    } else if (m.getId() == n.getPid()) {
                        m.getChildren().add(n);
                        n.setParentNode(m);
                    }
                }
            }
        }
        return nodes;
    }


    /**
     * 读取excel文件中每一行的内容
     *
     * @param row
     * @param c
     * @param formulaEvaluator
     * @return
     */
    private static String getCellAsString(Row row, int c, FormulaEvaluator formulaEvaluator) {
        String value = "";
        try {
            Cell cell = row.getCell(c);
            CellValue cellValue = formulaEvaluator.evaluate(cell);
            switch (cellValue.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    value = "" + cellValue.getBooleanValue();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    double numericValue = cellValue.getNumberValue();
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        double date = cellValue.getNumberValue();
                        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
                        value = formatter.format(HSSFDateUtil.getJavaDate(date));
                    } else {
                        value = "" + numericValue;
                    }
                    break;
                case Cell.CELL_TYPE_STRING:
                    value = "" + cellValue.getStringValue();
                    break;
                default:
                    break;
            }
        } catch (NullPointerException e) {
        }
        return value;
    }
}